package com.jse;

import java.io.IOException;
import java.util.Properties;

import javax.script.ScriptException;

public class Errs {
	
	private final static Properties prop=Lang.properties("/META-INF/jse/errs.properties");
	
	public static RuntimeException rt(Throwable e) {
		if(e instanceof RuntimeException ex)return ex;
		return new RuntimeException(e);
	}
	public static IOException io(Throwable e) {
		if(e instanceof IOException ex)return ex;
		return new IOException(e);
	}

	public static String message(Throwable e) {return message(e,null);}
	public static String message(Throwable e,StringBuilder s) {
		StringBuilder sb=s==null?new StringBuilder("errs:"):s;
		if(e.getStackTrace().length>1) {
			var t=e.getStackTrace()[1];
			sb.append(t.getClassName()+"."+t.getMethodName()+":"+t.getLineNumber());
		}
		sb.append(" ");
		if(e instanceof RuntimeException) {
			if(e.getCause()!=null) {
				return message(e.getCause(),sb);
			}else {
				return sb.append(e.getMessage()).toString();
			}
		}else if(e instanceof ScriptException se) {
			return sb.append("js err:").append(se.getFileName()).append(se.getLineNumber()).append(':')
					.append(se.getColumnNumber()).append(" msg:").append(e.getMessage()).toString();
		}else {
			if(prop.containsKey(e.getClass().getName())) {
				return sb.append(prop.getProperty(e.getClass().getName())+e.getMessage()).toString();
			}
			return sb.append(e.getClass().getName()+" : "+e.getMessage()).toString();
		}
	}
}
